package fragments;

import helper.FBHelper;
import helper.GetFBUserPhotoHelper;
import helper.HttpHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.Response;
import com.matchcalendar.R;

import dataFormat.FBUser;
import factories.ActivityIconListFactory;
import factories.DayListFactory;
import activities.MatchActivity;
import activities.MatchActivity.GroupState;
import activities.MatchActivity.ListViewGroupsState;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class GroupListFragment extends Fragment {
	private ListViewGroupsAdapter listViewGroupsAdapter;
	private List<String> activityIDList = new ArrayList<String>();
	private List<View> viewList = new ArrayList<View>();
	private MatchActivity.ListViewGroupsState state;
	
	public GroupListFragment(MatchActivity.ListViewGroupsState state) {
		this.state = state;
	}
	
	public List<View> getViewList() {
		return viewList;
	}
	
	public List<String> getActivityIDList() {
		return activityIDList;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		ListView listViewGroups = new ListView(getActivity());
		
		listViewGroupsAdapter = new ListViewGroupsAdapter(getActivity(),
				android.R.layout.simple_list_item_1, viewList);
		listViewGroups.setAdapter(listViewGroupsAdapter);
		listViewGroups.setOnItemClickListener(new ListViewGroupsItemClick());
		return listViewGroups;
	}
	
	private class ListViewGroupsAdapter extends ArrayAdapter<View> {
		public ListViewGroupsAdapter(Context context, int textViewResourceId, List<View> objects) {
			super(context, textViewResourceId, objects);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			return getItem(position);
		}
	}
	
	private class ListViewGroupsItemClick implements ListView.OnItemClickListener {
		private String activityID;

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
			activityID = activityIDList.get(index);
			new GetActivityJoinFriends().execute();
		}
		
		private class GetActivityJoinFriends extends AsyncTask<String, Void, String> {
			private ProgressDialog getReplyProDialog;
			private Map<String, FBUser> idFriendMap = new HashMap<String, FBUser>();
			private Set<FBUser> notReplyYet = new HashSet<FBUser>();
			private Set<FBUser> notJoin = new HashSet<FBUser>();
			private Set<FBUser> join = new HashSet<FBUser>();
			
			@Override
			protected void onPreExecute() {
				getReplyProDialog = ProgressDialog.show(getActivity(), "取得回覆資訊", "正在取得朋友回覆資訊...");
				getReplyProDialog.setCancelable(false);
			}

			@Override
			protected String doInBackground(String... params) {
				String respJsonStr = null;
				
				try {
					JSONObject reqJsonObj = new JSONObject();
					
					reqJsonObj.put("id", activityID);
					HttpResponse resp = HttpHelper.executePost(
							"http://iculture.twgg.org/activity/getFriendJoinActivity.php", reqJsonObj.toString());
					respJsonStr = EntityUtils.toString(resp.getEntity());
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (ParseException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return respJsonStr;
			}
			
			@Override
			protected void onPostExecute(String result) {
				try {
					JSONArray friendsJsonArr = new JSONArray(result);
					String where = null;
					
					for (int i=0; i<friendsJsonArr.length(); i++) {
						JSONObject friendJsonObj = friendsJsonArr.getJSONObject(i);
						String id = friendJsonObj.getString("id");
						FBUser friend = new FBUser(id, null, null);
						
						idFriendMap.put(id, friend);
						switch (friendJsonObj.getInt("state")) {
							case 0:
								notReplyYet.add(friend);
								break;
							case 1:
								notJoin.add(friend);
								break;
							case 2:
								join.add(friend);
						}
						if (i == 0)
							where = "uid = " + id;
						else
							where += " or uid = " + id;
					}
					new GetFriendNameFBHelper(where).ensureSessionOpenAndDoSomething(getActivity());
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			private class GetFriendNameFBHelper extends FBHelper {
				private String where;				

				public GetFriendNameFBHelper(String where) {
					this.where = where;
				}

				@Override
				protected void doAfterEnsureSessionOpen() {
					fqlQuery("uid, name", "user", where, null, null, null, null);
				}

				@Override
				protected void doAfterFqlQuery(Response response) {
					try {
						JSONArray dataJsonArr = response.getGraphObject().getInnerJSONObject()
								.getJSONArray("data");
						View view = View.inflate(getActivity(), R.layout.custom_response_invite_view, null);
						LinearLayout linearLayoutNotReplyYet =
								(LinearLayout)view.findViewById(R.id.linearLayoutNotReplyYet);
						LinearLayout linearLayoutNotJoin =
								(LinearLayout)view.findViewById(R.id.linearLayoutNotJoin);
						LinearLayout linearLayoutJoin =
								(LinearLayout)view.findViewById(R.id.linearLayoutJoin);
						AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity())
						.setTitle("揪團邀請答覆情形").setView(view);
						
						getReplyProDialog.cancel();
						for (int i=0; i<dataJsonArr.length(); i++) {
							JSONObject dataJsonObj = dataJsonArr.getJSONObject(i);
							
							idFriendMap.get(dataJsonObj.getString("uid")).setName(dataJsonObj.getString("name"));
						}
						addNamePhotos(linearLayoutNotReplyYet, notReplyYet);
						addNamePhotos(linearLayoutNotJoin, notJoin);
						addNamePhotos(linearLayoutJoin, join);
						if (state == ListViewGroupsState.ING) {
							dialogBuilder
							.setNegativeButton("取消", null)
							.setPositiveButton("確定揪團", new SureGroupButtonClick())
							.show();
						}
						else if (state == ListViewGroupsState.COMPLETE ||
								state == ListViewGroupsState.NOTJOIN || state == ListViewGroupsState.JOIN) {
							dialogBuilder
							.setPositiveButton("確定", null)
							.show();
						}
						else if (state == ListViewGroupsState.NOTREPLYYET) {
							dialogBuilder
							.setNegativeButton("不參加", new NotJoinButtonClick())
							.setPositiveButton("參加", new JoinButtonClick())
							.show();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				
				private void addNamePhotos(LinearLayout layout, Set<FBUser> fbUserSet) {
					if (fbUserSet.size() == 0) {
						TextView nothing = new TextView(getActivity());
						
						nothing.setText("無");
						layout.addView(nothing);
					}
					else {
						for (FBUser friend: fbUserSet) {
							TextView namePhoto = new TextView(getActivity());
							Drawable defaultIcon = getResources().getDrawable(
									R.drawable.com_facebook_profile_default_icon);
							
							namePhoto.setCompoundDrawablesWithIntrinsicBounds(null, defaultIcon, null, null);
							namePhoto.setGravity(Gravity.CENTER_HORIZONTAL);
							namePhoto.setText(friend.getName());
							if (friend.getPhoto() == null)
								new GetFriendPhotos(namePhoto).execute(friend);
							else {
								Drawable drawableBitmap = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(
										friend.getPhoto(), defaultIcon.getIntrinsicWidth(), defaultIcon.getIntrinsicHeight(), true));
								
								namePhoto.setCompoundDrawablesWithIntrinsicBounds(null, drawableBitmap, null, null);
							}
							layout.addView(namePhoto);
						}
					}
				}
				
				private class GetFriendPhotos extends GetFBUserPhotoHelper {
					private TextView namePhoto;
					
					public GetFriendPhotos(TextView namePhoto) {
						this.namePhoto = namePhoto;
					}

					@Override
					protected void onPostExecute(FBUser fbUser) {
						Drawable defaultIcon = getResources().getDrawable(R.drawable.com_facebook_profile_default_icon);
						Drawable drawableBitmap = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(
								fbUser.getPhoto(), defaultIcon.getIntrinsicWidth(), defaultIcon.getIntrinsicHeight(), true));
						
						namePhoto.setCompoundDrawablesWithIntrinsicBounds(null, drawableBitmap, null, null);
					}
				}
				
				private class SureGroupButtonClick implements DialogInterface.OnClickListener {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						new PostFinishGroup().execute();
					}
					
					private class PostFinishGroup extends AsyncTask<Void, Void, Void> {
						ProgressDialog finishGroupProDialog;
						
						@Override
						protected void onPreExecute() {
							finishGroupProDialog = ProgressDialog.show(getActivity(), "完成揪團",
									"正在完成揪團...");
							finishGroupProDialog.setCancelable(false);
						}

						@Override
						protected Void doInBackground(Void... params) {
							try {
								JSONObject reqJsonObj = new JSONObject();
								
								reqJsonObj.put("id", activityID);
								HttpHelper.executePost(
										"http://iculture.twgg.org/activity/finishActivity.php", reqJsonObj.toString());
							} catch (JSONException e) {
								e.printStackTrace();
							}
							return null;
						}
						
						@Override
						protected void onPostExecute(Void result) {
							finishGroupProDialog.cancel();
							((MatchActivity)getActivity()).reloadGroups();
						}
					}
				}
				
				private class NotJoinButtonClick implements DialogInterface.OnClickListener {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						new PostNotJoinGroup().execute();
					}
					
					private class PostNotJoinGroup extends AsyncTask<Void, Void, Void> {
						private ProgressDialog notJoinDialog;
						
						@Override
						protected void onPreExecute() {
							notJoinDialog = ProgressDialog.show(getActivity(), "不參加此揪團",
									"告知主揪人不參加此揪團...");
							notJoinDialog.setCancelable(false);
						}

						@Override
						protected Void doInBackground(Void... params) {
							try {
								JSONObject reqJsonObj = new JSONObject();
								String myFBID =
										((MatchActivity)getActivity()).getIntent().getExtras().getString("myFBID");
								
								reqJsonObj.put("fbID", myFBID);
								reqJsonObj.put("acID", activityID);
								HttpHelper.executePost(
										"http://iculture.twgg.org/activity/notJoinActivity.php", reqJsonObj.toString());
							} catch (JSONException e) {
								e.printStackTrace();
							}
							return null;
						}
						
						@Override
						protected void onPostExecute(Void result) {
							notJoinDialog.cancel();
							((MatchActivity)getActivity()).reloadGroups();
						}
					}
				}
				
				private class JoinButtonClick implements DialogInterface.OnClickListener {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						new PostJoinGroup().execute();
					}
					
					private class PostJoinGroup extends AsyncTask<Void, Void, Void> {
						private ProgressDialog joinDialog;
						
						@Override
						protected void onPreExecute() {
							joinDialog = ProgressDialog.show(getActivity(), "參加此揪團",
									"告知主揪人參加此揪團...");
							joinDialog.setCancelable(false);
						}

						@Override
						protected Void doInBackground(Void... params) {
							try {
								JSONObject reqJsonObj = new JSONObject();
								String myFBID =
										((MatchActivity)getActivity()).getIntent().getExtras().getString("myFBID");
								
								reqJsonObj.put("fbID", myFBID);
								reqJsonObj.put("acID", activityID);
								HttpHelper.executePost(
										"http://iculture.twgg.org/activity/joinActivity.php", reqJsonObj.toString());
							} catch (JSONException e) {
								e.printStackTrace();
							}
							return null;
						}
						
						@Override
						protected void onPostExecute(Void result) {
							joinDialog.cancel();
							((MatchActivity)getActivity()).reloadGroups();
						}
					}
				}
			}
		}
	}
	
	public void addGroupView(JSONArray groupJsonArr) {
		try {
			List<Integer> iconList = ActivityIconListFactory.newArrayList();
			List<String> dayList = DayListFactory.newArrayList();
			
			for (int i=0; i<groupJsonArr.length(); i++) {
				JSONObject groupJsonObj = groupJsonArr.getJSONObject(i);
				String activityID = groupJsonObj.getString("id");
				int iconID = iconList.get(groupJsonObj.getInt("icon"));
				String name = groupJsonObj.getString("name");
				String place = groupJsonObj.getString("place");
				String date = groupJsonObj.getString("date");
				String day = dayList.get(groupJsonObj.getInt("day"));
				String startTime = groupJsonObj.getString("startTime");
				String overTime = groupJsonObj.getString("overTime");
				String timeRange = startTime.substring(0, startTime.length() - 3) + "~" +
				overTime.substring(0, overTime.length() - 3);
				int otherState = groupJsonObj.getInt("otherState");
				View view = View.inflate(getActivity(), R.layout.custom_group_view, null);
				
				((ImageView)view.findViewById(R.id.imageViewIcon)).setImageResource(iconID);
				if (otherState == 1)
					((ImageView)view.findViewById(R.id.imageViewSmallIcon)).setImageResource(R.drawable.tick);
				((TextView)view.findViewById(R.id.textViewName)).setText("名稱: " + name);
				((TextView)view.findViewById(R.id.textViewPlace)).setText("地點: " + place);
				((TextView)view.findViewById(R.id.textViewDate)).setText("日期: " + date + " 星期" + day);
				((TextView)view.findViewById(R.id.textViewTimeRange)).setText("時間: " + timeRange);
				if (((MatchActivity)getActivity()).getNowGroupState() == GroupState.FRIENDSGROUP) {
					new GetMainGrouperName(groupJsonObj.getString("fbId"),
							(TextView)view.findViewById(R.id.textViewMainGrouper)).ensureSessionOpenAndDoSomething(getActivity());
				}
				viewList.add(view);
				activityIDList.add(activityID);
			}
			listViewGroupsAdapter.notifyDataSetChanged();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	private class GetMainGrouperName extends FBHelper {
		private String id;
		private TextView textViewName;

		public GetMainGrouperName(String id, TextView textViewName) {
			this.id = id;
			this.textViewName = textViewName;
		}

		@Override
		protected void doAfterEnsureSessionOpen() {
			fqlQuery("name", "user", "uid = " + id, null, null, null, null);
		}

		@Override
		protected void doAfterFqlQuery(Response response) {
			try {
				JSONArray dataJsonArr = response.getGraphObject().getInnerJSONObject().getJSONArray("data");
				String name = dataJsonArr.getJSONObject(0).getString("name");
				
				textViewName.setText("主揪者: " + name);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}
}
